import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';

import 'fluro_support_application.dart';
import 'fluro_support_base_router.dart';

class FSRoutes {
  static FSRoutes _instance;

  List<FSBaseRouter> _listRouter = [];

  static FSRoutes init(Router router, List<FSBaseRouter> listRouter,
      {Widget widgetNotFound}) {
    if (_instance == null) {
      _instance =
          FSRoutes._(router, listRouter, widgetNotFound: widgetNotFound);
    }
    return _instance;
  }

  FSRoutes._(Router router, List<FSBaseRouter> listRouter,
      {Widget widgetNotFound}) {
    FSApplication.router = router;

    /// 指定路由跳转错误返回页
    router.notFoundHandler = Handler(
        handlerFunc: (BuildContext context, Map<String, List<String>> params) {
      debugPrint("Routes >>> 404 未找到目标页");
      return widgetNotFound ?? Text("404 未找到目标页");
    });

    //每次初始化前 先清除集合 以免重复添加
    _listRouter.clear();

    /// 各自路由由各自模块管理，统一在此添加初始化
    _listRouter.addAll(listRouter);

    /// 初始化路由 循环遍历取出每个子router进行初始化操作
    _listRouter.forEach((routerProvider) {
      routerProvider.initRouter(router);
    });
  }

  static RouteFactory generator() {
    if (FSApplication.router == null) {
      throw Exception(
          "请正确对FSRoutes进行初始化: FSRoutes.init(Router router, List<FSBaseRouter> listRouter, {Widget widgetNotFound})");
    }
    return FSApplication.router.generator;
  }

  static Router router() {
    if (FSApplication.router == null) {
      throw Exception(
          "请正确对FSRoutes进行初始化: FSRoutes.init(Router router, List<FSBaseRouter> listRouter, {Widget widgetNotFound})");
    }
    return FSApplication.router;
  }
}
